<script setup lang="ts">
import { nextTick, onMounted, ref, type Ref, type UnwrapRef, watch } from 'vue'
import { microServiceHttpServer } from '@/apis/MicroServiceHttpServer.js'
import { ApplicationStatusCodeEnum } from '@/enum/ApplicationStatusCodeEnum.js'
import { UserNameAndPasswordDto } from '@/dto/UserNameAndPasswordDto'
import {useLocalInformationStore} from '@/stores/LocalInformation'

const infoStore = useLocalInformationStore()

const loginFormRef = ref(null)
const formContainerRef = ref(null)
const account = ref(null)
const password = ref(null)
const submit = ref(null)
const closeButton = ref(null)


const canSendVerificationCodeMail = ref(true)
const currentSendMailTimer = ref(60)
let sendMailTimerInterval = 0
const emailInputEl = ref(null)
const verificationFormRef = ref(null)
const inPlaceModifyPasswordFormRef = ref(null)
const inPlaceModifyUsernameFormRef = ref(null)
const isRegisterSuccess = ref(false)
const usernameAndPasswordDto: Ref<UnwrapRef<UserNameAndPasswordDto>> = ref(new UserNameAndPasswordDto(-1, '', '', ''))
const loginStep = ref(0)//0为登录表单，1 为注册表单，2 为提示修改默认密码表单，3 为提示修改默认名称表单
const emit = defineEmits(['closeForm', 'loginSuccess', 'registerSuccess', 'registerFinished'])


function formVerticalCentering() {
  if (formContainerRef.value) {
    formContainerRef.value.style.top = `calc((100vh - ${formContainerRef.value.clientHeight}px) / 2)`
  }
}


async function increment() {
  await nextTick()
  // 现在 DOM 已经更新了
}

function onCloseButtonClick() {
  emit('closeForm')
  loginStep.value = 0
}


function submitLoginForm() {
  microServiceHttpServer.postForm(new FormData(loginFormRef.value))
    .then(response => {
      let msg = JSON.parse(response.data)
      if (msg.code === ApplicationStatusCodeEnum.BAD_CREDENTIALS) {
        console.log('密码不对哦')
      } else if (msg.code === ApplicationStatusCodeEnum.USER_NOT_FOUND) {
        console.log('木有这个用户')
      } else if (msg.code === ApplicationStatusCodeEnum.NO_CREDENTIALS_PROVIDED) {
        console.log('没有认证信息')
      } else if (msg.code === ApplicationStatusCodeEnum.OK) {
        console.log('登录成功')
        emit('loginSuccess')
      } else {
        console.log('我超')
      }
    })

}

function onSubmitLoginSuccess() {
  loginStep.value = 2
}

function wannaRegister() {
  if (loginStep.value === 0) {
    loginStep.value = 1
  }
}

function backToLoginForm() {
  loginStep.value = 0
}

function sendVerificationCode() {
  let email = emailInputEl.value.value
  console.log(email)
  if (!email) {
    console.log('填写你的邮件地址')
    return
  }
  canSendVerificationCodeMail.value = false
  sendMailTimerInterval = setInterval(() => {
    if (currentSendMailTimer.value > 0) {
      currentSendMailTimer.value--
    } else {
      canSendVerificationCodeMail.value = true
      clearInterval(sendMailTimerInterval)
    }
  }, 1000)
  microServiceHttpServer.requestSendVerificationCode(email).then(response => {
    let msg = JSON.parse(response.data)
    if (msg.code === ApplicationStatusCodeEnum.ALREADY_EXISTS) {
      console.log('邮箱已经被注册了哦')
    } else if (msg.code === ApplicationStatusCodeEnum.BAD_REQUEST) {
      console.log('服务器娘说你的邮箱有点问题')
    } else if (msg.code === ApplicationStatusCodeEnum.OK) {
      console.log('验证码已经发送到这个邮箱中了')
    } else {
      console.log('我超！')
    }
  })
}

function submitRegistration() {
  let form = new FormData(verificationFormRef.value)
  microServiceHttpServer.sendVerificationCode(form.get('email'), form.get('verificationCode'),infoStore.fingerprint).then(response => {
    let msg = JSON.parse(response.data)
    if (msg.code === ApplicationStatusCodeEnum.BAD_CREDENTIALS) {
      console.log('验证码不匹配哦')
    } else if (msg.code === ApplicationStatusCodeEnum.NOT_FOUND) {
      console.log('认证码不存在或者已经超时了')
    } else if (msg.code === ApplicationStatusCodeEnum.OK) {
      let data = msg.data
      console.log(data)
      usernameAndPasswordDto.value = new UserNameAndPasswordDto(data.id, data.username, data.password,
        data.inPlaceOperationToken)
      onSubmitLoginSuccess()
    } else {
      console.log('我超！')
    }
  })
}

function submitInPlaceModifyPasswordRequest() {
  let from = new FormData(inPlaceModifyPasswordFormRef.value)
  let password = from.get('password')
  console.log(password)
  loginStep.value = 3
  if (!password) {
    return
  }
  let dto = new UserNameAndPasswordDto(usernameAndPasswordDto.value.getId(), null, password, usernameAndPasswordDto.value.getInPlaceOperationToken())
  microServiceHttpServer.sendInPlaceModifyRequest(dto).then(response => {
    let msg = JSON.parse(response.data)
    if (msg.code === ApplicationStatusCodeEnum.OK) {
      console.log('修改成功')
    } else if (msg.code === ApplicationStatusCodeEnum.BAD_REQUEST) {
      console.log('只能修改自己的信息哦')
    } else if (msg.code === ApplicationStatusCodeEnum.NOT_FOUND) {
      console.log('用户不存在')
    } else if (msg.code === ApplicationStatusCodeEnum.OPERATION_FAILED) {
      console.log('五分钟已经过去了，你需要去个人空间修改')
    } else {
      console.log('我超！')
    }
  })
}

function submitInPlaceModifyUsernameRequest() {
  let from = new FormData(inPlaceModifyUsernameFormRef.value)
  let username = from.get('username')
  console.log(username)
  if (!username) {
    return
  }
  let dto = new UserNameAndPasswordDto(usernameAndPasswordDto.value.getId(), username, null, usernameAndPasswordDto.value.getInPlaceOperationToken())
  microServiceHttpServer.sendInPlaceModifyRequest(dto).then(response => {
    let msg = JSON.parse(response.data)
    if (msg.code === ApplicationStatusCodeEnum.OK) {
      console.log('修改成功')
    } else if (msg.code === ApplicationStatusCodeEnum.BAD_REQUEST) {
      console.log('只能修改自己的信息哦')
    } else if (msg.code === ApplicationStatusCodeEnum.NOT_FOUND) {
      console.log('用户不存在')
    } else if (msg.code === ApplicationStatusCodeEnum.OPERATION_FAILED) {
      console.log('五分钟已经过去了，你需要去个人空间修改')
    } else if (msg.code === ApplicationStatusCodeEnum.ALREADY_EXISTS) {
      console.log('用户名已存在')
    } else {
      console.log('我超！')
    }
  })

  emit('registerFinished')

}

onMounted(() => {
  // account.value.value = accountPlaceholder
  account.value.focus()
  // formVerticalCentering()
  watch(formContainerRef.value.clientHeight, formVerticalCentering, {
    immediate: false
  })
  window.addEventListener('resize', formVerticalCentering)
  closeButton.value.addEventListener('click', closeButton)
})

</script>

<template>
  <div class="login__form__background">
    <div class="login__form__container" ref="formContainerRef">
      <div class="left">
        <div class="text">
          <h1>记得吃饭</h1>
          <h4>SnowCrystal</h4>
        </div>
        <video loop autoplay>
          <source src="/Background/55b05a808062091eea5fdb59e5307067d6713fc7.webm" type="video/webm" />
          <source src="/Background/6e01ff8726f0ffc8a9edcaae590cf282de14e667.mp4" type="video/mp4" />
        </video>
      </div>

      <div class="right">
        <div class="close__button" ref="closeButton" @click="onCloseButtonClick"></div>
        <h4>{{ loginStep !== 0 ? '注册' : '登录' }}</h4>
        <template v-if="loginStep === 0">
          <form ref="loginFormRef"
                method="post">

            <input required id="account"
                   ref="account" class="bar" type="text" placeholder="用户名哦" name="username">
            <input required id="password" ref="password" placeholder="密码哦" class="bar" type="password"
                   name="password">
            <input id="rememberMe" type="hidden" name="remember-me" value="true">
            <input type="hidden" name="fingerprint" :value="infoStore.fingerprint">
            <input id="button" class="button" ref="submit" type="submit"
                   value="登录"
                   @click.prevent="submitLoginForm">

          </form>
        </template>

        <template v-else-if="loginStep===1">
          <form class="verification__form__root" ref="verificationFormRef">
            <div class="email__post__verification">
              <input type="email" placeholder="邮箱" name="email" style="float:left" class="bar" ref="emailInputEl"
                     required>
              <span v-if="canSendVerificationCodeMail" @click="sendVerificationCode"
                    style="cursor:pointer">发送验证码</span>
              <span v-else>{{ currentSendMailTimer }}</span>
            </div>
            <input type="text" placeholder="验证码" name="verificationCode" class="bar" required>
            <div class="submit__wrapper" style="place-content:center;">
            <span class="backward__to__login '" @click="backToLoginForm">
              <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"
                   style="fill: rgba(255,255,255,0.6);">
                <path d="M15 19V5l-8 7z"></path>
              </svg>
            </span>
              <input id="button" class="button" ref="submit" type="submit"
                     value='注册'
                     @click.prevent="submitRegistration">
            </div>
          </form>
        </template>

        <template v-else-if="loginStep===2">
          <form ref="inPlaceModifyPasswordFormRef">
            <p>
              注册成功，默认创建的密码已经发送到了你的邮箱中，你的默认密码是
              <span> {{ usernameAndPasswordDto ? usernameAndPasswordDto.getPassword() : '' }} </span>
              5分钟内可以选择立即修改一次密码哦,不需要则直接下一步
            </p>
            <input required type="password" class="bar" ref="inPlace" name="password" placeholder="修改默认密码(可选)">
            <input type="submit" class="button" @click.prevent="submitInPlaceModifyPasswordRequest" value="下一步">
          </form>
        </template>

        <template v-else-if="loginStep===3">
          <form ref="inPlaceModifyUsernameFormRef">
            <p>
              你的用户名默认是 <span> {{ usernameAndPasswordDto ? usernameAndPasswordDto.getUsername() : '' }} </span>
              现在可以立即修改一次用户名哦
            </p>
            <input required type="text" class="bar" name="username" placeholder="修改默认用户名(可选)" />
            <input type="submit" class="button" @click.prevent="submitInPlaceModifyUsernameRequest" value="完成">
          </form>
        </template>
        <div class="operator">
          <a class="a1" href="#" @click.prevent="wannaRegister">注册账号</a>
          <a class="a2" href="#">修改密码</a>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.email__post__verification {
  display: flex;
  flex-wrap: nowrap;
  width: 85%;

  span {
    place-content: center;
    display: inline-block;
    background-color: #706eff;
    height: 100%;
    width:15%;
    text-align: center;
  }
}


.verification__form__root {
  display: flex;
  padding: var(--spacing-xs);
  flex-direction: column;
  align-items: center;
  row-gap: var(--spacing-l);
}

input:invalid {
  border-bottom-color: #d72222;
}

.login__form__container {
  backdrop-filter: blur(10px);
  aspect-ratio: 2 / 1;
  top: calc(30vh - 180px);


}

form {
  padding: var(--spacing-xs);
  display: flex;
  flex-direction: column;
  align-items: center;
  row-gap: var(--spacing-l);
  height: 100%;
}

#account {
  position: relative;
}

#account::before {
  content: '"\eee2"';
}

input {
  color: darkslateblue;
  transition: all 0.4s ease-in-out;
}

input:focus {
  color: #615fff;
  outline: none;
}

.login__form__container .right h4 {
  color: #706eff;
}
</style>


<style scoped lang="scss">
.operator {
  height: 100%;
  font-size: 30px;
  display: flex;
  align-items: center;
  justify-content: space-evenly;
}
</style>

<style scoped lang="scss">
.login__form__background {
  position: absolute;
  z-index: 5;
  height: 100%;
  width: 100%;
}

.login__form__container {
  position: sticky;
  overflow: hidden;
  /*将溢出父元素的部分删去*/
  display: grid;
  grid-template-columns: 0.618fr 1fr;
  /*定义为弹性容器*/
  width: 80rem;
  background-color: rgba(255, 255, 255, 0.6);
  border-radius: 1.5rem;
  margin: 0 auto;
  box-shadow: 1rem 0.1rem 1rem 0rem rgba(144, 129, 241, 0.5);
}

.login__form__container .left {
  border-right: rgba(60, 63, 247, 0.48) 2px solid;
  position: relative;
  background-color: skyblue;

}

/*左边 图片 插入*/
.login__form__container .left::before {
  content: '';
  width: 100%;
  position: absolute;
  height: 100%;
  background-image: url(2233.webp);
  background-position: center;
  background-size: cover;
  opacity: 80%;
}

/*右边样式属性设置*/
.login__form__container .right {
  position: relative;
  user-select: none;
  display: grid;
  grid-template-rows: 1fr 2fr 1fr;
  flex-direction: column;
  align-items: center;
}

/*右侧标题设置*/
.login__form__container .right h4 {
  display: flex;
  place-content: center;
  font-size: 2.4rem;
  margin-top: 5rem;
}


/*右侧 登录框设置*/
.login__form__container .right input.bar {
  outline: none;
  /* 清除登录框 自带的 突出框*/
  width: 85%;
  height: 5rem;
  font-size: 1.4rem;
  border: none;
  border-bottom: 2px solid;
  border-bottom-color: rgb(144, 129, 241);
  border-radius: 1px;
  background-color: rgba(0, 0, 0, 0);
}

/*设置登录按钮*/
.login__form__container .right input.button {

  width: 60%;
  height: 80px;
  background-image: linear-gradient(120deg, #E0C3FC, #8EC5FC);
  border: none;
  /*清除边框 自带的都不要*/
  border-radius: 0.7rem;
  color: #ffffff;
  font-size: 1.8rem;
}

/*鼠标悬浮与按钮上时，按钮的状态*/
.login__form__container .right input.button:hover {
  box-shadow: 0 0 2rem -0.5rem rgba(0, 0, 0, 0.2);
}


.submit__wrapper {
  width: 85%;
  height: 80px;
  display: flex;
  column-gap: var(--spacing-xs);
}

.backward__to__login {
  display: block;
  height: 100%;
  float: left;
  width: 80px;
  background-color: #7c7cf0;
  border-radius: 0.7rem;
  transition: all 0.8s cubic-bezier(1, 0, 0, 1);
  cursor: pointer;

  svg {
    height: 100%;
    width: 100%;
  }
}

.backward__to__login:hover {
  background-color: #d3a3ff;
  box-shadow: 0 0 2rem -0.5rem rgb(126, 160, 193);
}

/*设置超链接  */
.login__form__container .right form .operator a {
  font-size: 1.5rem;
  color: #E0C3FC;
  text-decoration: none;
}

/*当鼠标悬浮于超链接上面时，超链接的样式*/
.login__form__container .right form .operator a:hover {
  color: #d3a3ff;
}

/*以下两个css为设置两个超链接的位置*/
.login__form__container .right form .operator a.a1 {
  margin-left: 6px;
  float: left;
}

.login__form__container .right form .operator a.a2 {
  float: right;
  margin-right: 6px;
}

#rememberMe {
  position: absolute;

}
</style>

<style scoped lang="scss">
.left video {
  height: 100%;
  width: 100%;
  object-fit: cover;
  position: absolute;
  filter: blur(3px);
}

.left .text {
  user-select: none;
  font-family: "LiLang", sans-serif;
  position: absolute;
  z-index: 5;
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  place-content: center;
}

.text h1 {
  text-align: center;
  color: white;
}

.text h4 {
  text-align: center;
  font-style: italic;
}
</style>


<style scoped lang="scss">
.close__button {
  position: absolute;
  height: 100px;
  width: 100px;
  background-image: url("/icons/close.svg");
  background-size: cover;
  right: 0;
  top: 0;
  transition: all 0.5s ease-in-out;
}

.close__button:hover {
  background-color: rgba(229, 180, 43, 0.51);
}
</style>
